package com.snail.config;

import com.snail.config.RabbitConfig;
import com.snail.model.pojo.mall.BizOrderDetail;
import com.snail.service.BizOrderDetailService;
import com.snail.service.IBizOrderService;
import com.snail.service.IBizProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OrderDeadLetterConsumer {

    private static final Logger logger = LoggerFactory.getLogger(OrderDeadLetterConsumer.class);

    @Autowired
    private IBizOrderService orderService;
    @Autowired
    private BizOrderDetailService orderDetailService;

    @Autowired
    private IBizProductService productService;
    /**
     * 监听死信队列，处理过期订单
     */
    @RabbitListener(queues = RabbitConfig.ORDER_DEAD_LETTER_QUEUE)
    public void processExpiredOrder(String orderNo) {
        try {
            logger.info("开始处理过期订单: {}", orderNo);

            // 查询订单状态，只有未支付的订单才删除
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.snail.model.pojo.mall.BizOrder> queryWrapper =
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);

            com.snail.model.pojo.mall.BizOrder order = orderService.getOne(queryWrapper);

            if (order != null) {
                // 检查订单状态（假设0是未支付状态）
                if (order.getOrderStatus() == 0) {
                    // 删除未支付的过期订单
                    boolean deleted = orderService.remove(queryWrapper);
                    if (deleted) {
                        logger.info("成功删除过期未支付订单: {}", orderNo);
                    } else {
                        logger.error("删除过期订单失败: {}", orderNo);
                    }

                    List<BizOrderDetail> orderDetails = orderDetailService.getDetailsByOrderNo(orderNo);

                    if (orderDetails != null && !orderDetails.isEmpty()) {
                        // 2. 恢复商品库存
                        for (BizOrderDetail detail : orderDetails) {
                            if (detail.getProductId() != null && detail.getQuantity() != null) {
                                // 调用增加库存方法
                                productService.increaseStock(
                                        detail.getProductId().intValue(),
                                        detail.getQuantity()
                                );
                                System.out.println("恢复商品 " + detail.getProductId() + " 库存 " + detail.getQuantity() + " 件");
                            }
                        }
                    }

                } else {
                    logger.info("订单已支付或状态已变更，无需删除: {}", orderNo);
                }
            } else {
                logger.warn("订单不存在，可能已被删除: {}", orderNo);
            }
            // 1. 查询订单详情

        } catch (Exception e) {
            logger.error("处理过期订单时发生错误: {}", orderNo, e);
        }
    }
}